package com.baihan.angus.app.game.common.receiver;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import androidx.annotation.RequiresPermission;

import com.baihan.angus.app.game.basic.BaseApplication;
import com.baihan.angus.app.game.basic.utils.Loog;
import com.baihan.angus.app.game.common.R;
import com.baihan.angus.app.game.basic.event_bus.LiveDataEvent;
import com.baihan.angus.app.game.basic.event_bus.BusEventCode;

import org.greenrobot.eventbus.EventBus;


public class NetworkChangedReceiver extends BroadcastReceiver {

    private static final String LOGTAG = "NetworkChangedReceiver";

    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager == null) return;
            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            if (activeNetwork != null) {
                if (activeNetwork.isConnected()) {
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                        Loog.dTag(LOGTAG, "网络连接发生变化，当前WiFi连接可用，正在尝试重连。");
                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        Loog.dTag(LOGTAG, "网络连接发生变化，当前移动连接可用，正在尝试重连。");
                    }
                    EventBus.getDefault().post(new LiveDataEvent(BusEventCode.NET_STATUS_OK));
                } else {
                    Loog.dTag(LOGTAG, BaseApplication.getApplication().getString(R.string.noNetwork));
                    EventBus.getDefault().post(new LiveDataEvent(BusEventCode.NET_STATUS_DISCONNECT));
                }
            }
        }
    }
}